<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" class="mb-10px"/>
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="{ children: 'children', label: 'name' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="deptTreeRef"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleDeptClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="searchForm" ref="searchFormRef" size="small" inline v-show="showSearch">
          <el-form-item label="用户名称" prop="like.user_name">
            <el-input v-model="searchForm.like.user_name" placeholder="请输入用户名称" clearable class="w-140px" @keyup.enter.native="search"/>
          </el-form-item>
          <el-form-item label="手机号码" prop="like.phone">
            <el-input v-model="searchForm.like.phone" placeholder="请输入手机号码" clearable class="w-140px" @keyup.enter.native="search"/>
          </el-form-item>
          <el-form-item label="状态" prop="where.status">
            <el-select v-model="searchForm.where.status" placeholder="用户状态" clearable class="w-120px">
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="子部门" prop="contain">
            <el-select v-model="searchForm.contain" placeholder="子部门" class="w-120px">
              <el-option label="不包含" :value="0" />
              <el-option label="包含" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button icon="el-icon-refresh"  @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="mb-8px reset">
          <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPerm="['system:admin:add']">新增</el-button>
          <el-button type="success" plain icon="el-icon-edit" @click="handleEdit" v-hasPerm="['system:admin:edit']" :disabled="ids.length !== 1">修改</el-button>
          <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete" v-hasPerm="['system:admin:delete']" :disabled="!ids.length">删除</el-button>
          <el-button type="info" plain icon="el-icon-upload2" @click="handleImport" v-hasPerm="['system:admin:import']">导入</el-button>
          <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPerm="['system:admin:export']">导出</el-button>
          <right-toolbar :showSearch.sync="showSearch" @refresh="getList" :columns="columns" />
        </div>

        <el-table v-loading="loading" :data="listData" @selection-change="handleSelection">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            v-for="(item, field) in columns"
            :key="field"
            :prop="field"
            :label="item.label"
            align="center"
            :show-overflow-tooltip="!!item.overflow"
            :width="item.width"
            v-if="item.show"
          >
            <template slot-scope="{ row }">
              <span v-if="field === 'deptName'">{{ row.deptName.join(', ') }}</span>
              <span v-else-if="field === 'roleName'">{{ row.roleName.join(', ') }}</span>
              <span v-else-if="field === 'status'">
                <el-switch v-model="row.status" active-value="1" inactive-value="0" @change="handleStatus(row)" />
              </span>
              <span v-else-if="field === 'create_time'">{{ parseTime(row.create_time, '{y}-{m}-{d} {h}:{i}') }}</span>
              <span v-else>{{row[field]}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.id !== rootAdmin">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPerm="['system:admin:edit']">修改</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPerm="['system:admin:reset-pwd', 'system:admin:auth-role', 'system:admin:delete']">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleDelete" icon="el-icon-delete"
                    v-hasPerm="['system:admin:delete']">删除账号</el-dropdown-item>
                  <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                    v-hasPerm="['system:admin:reset-pwd']">重置密码</el-dropdown-item>
                  <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check"
                    v-hasPerm="['system:admin:auth-role']">分配角色</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize" @pagination="getList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <UserForm v-model="formShow" :row="formData" v-if="formShow" @submit="getList"/>

    <!-- 用户导入对话框 -->
    <admin-import v-model="uploadShow"/>

  </div>
</template>

<script>
import { listAdminApi, delAdminApi, changeAdminStatusApi, resetAdminPwdApi, exportAdminApi } from '@/api/system/admin'
import { selectDeptApi } from '@/api/system/dept'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import UserForm from './form'
import AdminImport from './import'

export default {
  name: 'Admin',
  dicts: ['sys_normal_disable'],
  components: { TreeSelect, UserForm, AdminImport },
  data() {
    return {
      formData: null,
      formShow: false,
      deptLoading: true,
      loading: true,
      ids: [],
      showSearch: true,
      total: 0,
      listData: [], // 管理员列表
      deptOptions: [], // 部门列表树
      deptName: undefined, // 部门筛选名称
      // 默认密码
      initPassword: undefined,
      // 查询参数
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        contain: 0,
        deptId: undefined,
        like: { user_name: undefined, phone: undefined},
        where: { status: undefined}
      },
      uploadShow: false,
      // 列信息
      columns: {
        id: { label: `编号`, show: true, width: 70 },
        user_name: { label: `用户名称`, show: true, overflow: true },
        nick_name: { label: `用户昵称`, show: true , overflow: true},
        deptName: { label: `部门`, show: true, overflow: true },
        roleName: { label: `角色`, show: true , overflow: true},
        phone: { label: `手机号码`, show: true, overflow: true },
        status: { label: `状态`, show: true },
        create_time: { label: `创建时间`, show: true, overflow: true },
      },
    };
  },
  watch: {
    deptName(val) {
      this.$refs.deptTreeRef.filter(val) // 根据名称筛选部门树
    }
  },
  computed: {
    rootAdmin() {
      return this.$store.getters.config?.root_admin_id || 0
    }
  },
  created() {
    this.getList()
    this.getDeptOptions()
    this.getConfig("sys.user.pwd").then(pwd => {
      this.initPassword = pwd || ''
    })
  },
  methods: {
    // 获取管理员列表
    getList() {
      this.loading = true
      listAdminApi(this.searchForm).then(res => {
        this.listData = res?.list || []
        this.total = res?.total
        this.loading = false
      })
    },
    // 获取部门列表
    getDeptOptions() {
      this.deptLoading = true
      selectDeptApi().then(res => {
        this.deptOptions = this.listToTree(res?.list || [])
        this.deptLoading = false
      })
    },
    // 查询重置页码
    search() {
      this.searchForm.pageNum = 1
      this.getList()
    },
    // 重置搜索框并查询
    reset() {
      this.resetForm('searchFormRef')
      this.search()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.formData = this.searchForm.deptId ? { deptId: this.searchForm.deptId } : null
      this.formShow = true
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.formData = { id: row?.id || (this.ids.length ? this.ids[0] : '') }
      if (!this.formData.id) return this.$modal.msgError('参数缺失')
      this.formShow = true
    },
    // 更多操作触发
    handleCommand(command, row) {
      if(command === 'handleResetPwd'){
        this.handleResetPwd(row)
      }else if(command === 'handleAuthRole'){
        this.handleAuthRole(row)
      }else if (command === 'handleDelete'){
        this.handleDelete(row)
      }
    },
    // 多选框事件
    handleSelection(selection) {
      this.ids = selection.map(item => item.id)
    },
    // 部门过滤搜索
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 部门树节点点击
    handleDeptClick(data) {
      this.searchForm.deptId = data.id
      this.search()
    },
    // 更改管理员状态
    handleStatus(row) {
      let text = row.status === "1" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.user_name + '"用户吗？').then(function() {
        return changeAdminStatusApi(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$modal.prompt(`请输入${row.user_name}的新密码`, '提示', {
        inputType: 'password',
        inputValue: this.initPassword,
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) return "不能包含非法字符：< > \" ' \\\ |"
        },
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: '用户密码长度必须介于 6 和 20 之间'
      }).then(({ value }) => {
        resetAdminPwdApi(row.id, value).then(() => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value)
          })
        }).catch(() => {})
    },
    /** 分配角色操作 */
    handleAuthRole(row) {
      const adminId = row?.id || ''
      if(!adminId) return this.$modal.msgWarning('参数缺失')
      this.$router.push({name: "AuthRole",params: {adminId}})
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row?.id || this.ids.join(',')
      if (!userIds) return this.$modal.msgWarning('未选择数据')
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
        return delAdminApi(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      exportAdminApi(this.searchForm)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.uploadShow = true
    },
  }
};
</script>
